package 每日一题;

public class 扁平化多级双向链表 {

    class Node {
        public int val;
        public Node prev;
        public Node next;
        public Node child;
    }

    public Node flatten(Node head) {
        if (head == null) return null;
        Node cur = head;
        // 向后遍历
        while (cur != null) {
            // 存在子链表，进行递归
            if (cur.child != null) {
                // 保留 next 节点
                Node next = cur.next;
                // 得到扁平化后的子链表，与之相连
                Node child = flatten(cur.child);
                cur.next = child;
                child.prev = cur;
                cur.child = null;
                // 连接原 next
                if (next != null) {
                    while (cur.next != null) {
                        cur = cur.next;
                    }
                    cur.next = next;
                    next.prev = cur;
                }
            }
            cur = cur.next;
        }
        return head;
    }
}
